package com.example.demo.limiter;

import org.springframework.util.Assert;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;

public class DemoTest {

    public static final String DATA_TIME_FORMAT_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    public static final String YYYYMMDD = "yyyyMMdd";

    public static void main(String[] args) {
        Date date = new Date();
        String s = format(date, YYYYMMDD);
        System.out.println(s);
    }

    /**
     * 字符串转换为对应日期(可能会报错异常)
     *
     * @param source  日期字符串
     * @param pattern 日期格式
     * @return 日期
     * @throws ParseException
     */
    public static Date stringToDate(String source, String pattern) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
            return simpleDateFormat.parse(source);
        } catch (ParseException e) {
            Assert.isTrue(false, "日期转换异常：格式=%s 数据=%s");
            return null;
        }
    }

    public static String format(Date currentDate, String pattern) {
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        return formatter.format(currentDate);
    }



    /**获取指定时间
     *
     * @param date
     * @param hour
     * @param minute
     * @param second
     * @return
     */
    public static Date getDesignationDate(Date date, int hour, int minute, int second) {
        Calendar c1 = Calendar.getInstance();
        c1.clear();
        c1.set(getYear(date), getMonth(date) - 1, getDay(date), hour, minute, second);
        return c1.getTime();
    }

    /**
     * 获取指定日期的年数
     */
    public static int getYear(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.YEAR);
    }


    /**
     * 获取指定日期的月数
     */
    public static int getMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.MONTH) + 1;
    }

    /**
     * 获取指定日期的天数
     */
    public static int getDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.DAY_OF_MONTH);
    }


}
